﻿using System.Collections.Generic;
using System.Text;
using System.Linq;

namespace TLang.Values
{
    public class UnionType : Value
    {

        public HashSet<Value> values = new HashSet<Value>();


        public UnionType()
        {

        }


        public static Value union(ICollection<Value> values)
        {
            UnionType u = new UnionType();
            foreach (Value v in values)
            {
                u.add(v);
            }
            if (u.size() == 1)
            {
                return u.first();
            }
            else
            {
                return u;
            }
        }


        public static Value union(params Value[] values)
        {
            UnionType u = new UnionType();
            foreach (Value v in values)
            {
                u.add(v);
            }
            if (u.size() == 1)
            {
                return u.first();
            }
            else
            {
                return u;
            }
        }


        public void add(Value value)
        {
            if (value is UnionType) {
                foreach (var item in ((UnionType)value).values)
                {
                    values.Add(item);
                }
            } else {
                values.Add(value);
            }
        }


        public int size()
        {
            return values.Count;
        }


        public Value first()
        {
            return values.First();
        }


        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Constants.PAREN_BEGIN).Append("U ");

            bool first = true;
            foreach (Value v in values)
            {
                if (!first)
                {
                    sb.Append(" ");
                }
                sb.Append(v);
                first = false;
            }

            sb.Append(Constants.PAREN_END);

            return sb.ToString();
        }
    }
}
